from socket import *
from select import *


class TcpServer:
    def __init__(self, ip="0.0.0.0", port=5555, target=None):
        self.ip = ip
        self.port = port
        self.target = target
        self.server = socket()
        self.server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
        self.server.bind((ip, port))
        self.rlist, self.olist, self.xlist = [self.server], [], []

    def server_forever(self):
        self.server.listen(3)
        print("listening from port %d" % self.port)
        # IO多路复用接收客户端请求
        while True:

            rs,ws,xs=select(self.rlist, self.olist, self.xlist)
            for item in rs:
                if item is self.server:
                    conn,address=item.accept()
                    print("connect from...",address)
                    self.rlist.append(conn)
                else:
                    # 处理请求
                    self.handle(item)
    def handle(self,conn):
        request=conn.recv(4096)
        if not request:
            self.rlist.remove(conn)
            conn.close()
            return
        # 提取内容 (字节串按行分割
        request_line=request.splitlines()[0]
        info=request_line.decode().split(" ")[1]
        if info=="/" or info[-5:]==".html":
            self.get_html(conn,info)
        else:
            self.get_data(conn)

    def get_html(self,conn,info):
        # 请求主页
        if info=="/":
            filename= "index.html"
        else:
            filename="image.html"
        try:
            fd=open(filename,encoding="utf-8")
        except Exception:
            # 网页不存在
            response="HTTP/1.1 404 Not Found\r\n"
            response+="Content-Type:text/html\r\n"
            response+="\r\n"
            response+="<h1>Sorry, you input a error page</h1>"
        else:
            # 网页存在
            response="HTTP/1.1 200 OK\r\n"
            response+="Content-Type:text/html\r\n"
            response+="\r\n"
            response=fd.read()
        finally:
            conn.send(response.encode("utf-8"))

    def get_data(self,conn):
        pass




if __name__=="__main__":
    tcp=TcpServer()
    tcp.server_forever()